package com.zhou.common.mybatis.template.shiro.config.shiro.service;


import com.zhou.common.lib.constants.Constants;
import com.zhou.common.lib.util.I18nUtil;
import com.zhou.common.lib.util.StringUtils;
import com.zhou.common.mybatis.template.shiro.config.ShiroConstants;
import com.zhou.common.mybatis.template.shiro.config.shiro.AsyncFactory;
import com.zhou.common.mybatis.template.shiro.config.shiro.AsyncManager;
import com.zhou.common.mybatis.template.shiro.config.shiro.exception.CaptchaException;
import com.zhou.common.mybatis.template.shiro.config.shiro.exception.UserBlockedException;
import com.zhou.common.mybatis.template.shiro.config.shiro.exception.UserNotExistsException;
import com.zhou.common.mybatis.template.shiro.config.shiro.exception.UserPasswordNotMatchException;
import com.zhou.common.mybatis.template.shiro.constants.UserConstants;
import com.zhou.common.mybatis.template.shiro.constants.UserStatus;
import com.zhou.common.mybatis.template.shiro.entity.SysUser;
import com.zhou.common.mybatis.template.shiro.service.ISysUserService;
import com.zhou.common.mybatis.template.shiro.utils.ServletUtils;
import com.zhou.common.mybatis.template.shiro.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysUserService userService;

/*    @Autowired
    private ISysMenuService menuService;*/

    /**
     * 登录
     */
    public SysUser login(String username, String password) {
        // 验证码校验
        if (ShiroConstants.CAPTCHA_ERROR.equals(ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18nUtil.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18nUtil.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18nUtil.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }

        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18nUtil.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }

        // 查询用户信息
        SysUser user = userService.selectUserByLoginName(username);

        if (user == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18nUtil.message("user.not.exists")));
            throw new UserNotExistsException();
        }

        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, I18nUtil.message("user.blocked", user.getRemark())));
            throw new UserBlockedException();
        }

        passwordService.validate(user, password);

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, I18nUtil.message("user.login.success")));
        setRolePermission(user);
        recordLoginInfo(user.getId());
        return user;
    }

    /**
     private boolean maybeEmail(String username)
     {
     if (!username.matches(UserConstants.EMAIL_PATTERN))
     {
     return false;
     }
     return true;
     }

     private boolean maybeMobilePhoneNumber(String username)
     {
     if (!username.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN))
     {
     return false;
     }
     return true;
     }
     */

    /**
     * 设置角色权限
     *
     * @param user 用户信息
     */
    public void setRolePermission(SysUser user) {
        /*List<SysRole> roles = user.getRoles();
        if (!roles.isEmpty() && roles.size() > 1) {
            // 多角色设置permissions属性，以便数据权限匹配权限
            for (SysRole role : roles) {
                Set<String> rolePerms = menuService.selectPermsByRoleId(role.getRoleId());
                role.setPermissions(rolePerms);
            }
        }*/
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser user = new SysUser();
        user.setId(userId);
        user.setLoginIp(ShiroUtils.getIp());
        user.setLoginDate(LocalDateTime.now());
        userService.updateUserInfo(user);
    }
}
